/*  HostMon/msntop - A simple program to monitor hosts on android
	Copyright (C) 2009 Devendra Laulkar

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation version 2 of the License. 

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.android.msntop;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class HostView extends Activity {

	private TextView name, status, comment, sshU, sshP, barcode;
	private Button ssh, back;
	private String defaultUser, hostName, defPort, gBarcode, gOptPath;

	private static final int EDIT = 0;
	private static final int DELETE = 1;
	private static final int HELP = 2;
	private static final int BARCODE = 3;


	public static final int HOST_EDITED = 2;
	public static final int HOST_DELETED = 3;

	public boolean edited = false;
	public boolean backToCalling = true;
	//	private String details[];

	public void onCreate(Bundle savedInstance)
	{
		super.onCreate(savedInstance);
		setContentView(R.layout.host2);

		name = (TextView) findViewById(R.id.name);
		status = (TextView) findViewById(R.id.status);
		comment = (TextView) findViewById(R.id.comment);
		ssh = (Button) findViewById(R.id.ssh);
		back = (Button) findViewById(R.id.back);
		sshU = (TextView) findViewById(R.id.view_sshuser);
		sshP = (TextView) findViewById(R.id.view_sshport);
		barcode = (TextView) findViewById(R.id.barcode);
		barcode.setText("");

		sshU.setNextFocusRightId(R.id.add_sshport);
		sshP.setNextFocusRightId(R.id.ssh);

		sshP.setSelectAllOnFocus(true);
		sshU.setSelectAllOnFocus(true);


		//back.requestFocus();
		//ssh.requestFocus();
		Bundle extras = getIntent().getExtras();

		if(extras != null)
		{
			hostName = extras.getString(Host.NAME);
			String hostStatus = extras.getString(Host.STATUS);
			String commentText= extras.getString(Host.COMMENT);

			String sshUser = extras.getString(Host.SSHUSER);
			String sshPort = extras.getString(Host.SSHPORT);

			gBarcode = extras.getString(Host.BARCODE);
			gOptPath = extras.getString(Host.OPTPATH);
			
			defaultUser = extras.getString(Msntop.DEFAULT_USER_KEY);
			defPort = extras.getString(Msntop.DEFAULT_PORT_KEY);

			if(hostName != null)
			{
				name.setText(hostName);
				//				details[0] = hostName;

			}
			if(hostStatus != null)
			{
				status.setText(hostStatus);
				if(hostStatus.equals(Msntop.UP))
				{
					status.setTextColor(Color.GREEN);
				}
				else
				{
					status.setTextColor(Color.RED);
				}
				//				details[1] = hostStatus;
			}

			if(commentText != null)
			{
				comment.setText(commentText);
				//details[2] = commentText;
			}

			if(sshUser == null || HostDbAdapter.UNSET_SSHUSER.equals(sshUser))
			{
				sshU.setText(defaultUser);
			}
			else
			{
				sshU.setText(sshUser);
			}
			if(sshPort.equals(HostDbAdapter.UNSET_SSHPORT))
			{
				sshP.setText(defPort);
			}
			else
			{
				sshP.setText(sshPort);
			}

			if(gBarcode == null || "".equals(gBarcode))
			{
				barcode.setText("");
			}
			else
			{
				barcode.setText("Barcode : " + gBarcode);
			}
			sshU.setCursorVisible(false);
			sshP.setCursorVisible(false);
			//back.setSelected(true);

		}

		sshU.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view)
			{
				sshU.setCursorVisible(true);
				sshU.setSelected(true);

			}
		});

		sshP.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view)
			{
				//sshP.setText(Integer.toString(-22),TextView.BufferType.EDITABLE);

				sshP.setCursorVisible(true);
				sshP.setSelected(true);

			}
		});
		sshU.setOnFocusChangeListener(new View.OnFocusChangeListener()
		{
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus)
				{
					sshU.setCursorVisible(true);
					sshU.setSelected(true);

				}
			}

		});

		sshP.setOnFocusChangeListener(new View.OnFocusChangeListener()
		{
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus)
				{
					sshP.setCursorVisible(true);
					sshP.setSelected(true);
				}
			}

		});

		back.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {

				if(edited)
				{
					Intent i = new Intent();
					i.putExtras(createBundle());
					setResult(HOST_EDITED, i);
					edited = false;
				}
				else
				{
					setResult(RESULT_OK);
				}
				finish();
			}
		});

		ssh.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				String user = sshU.getText().toString();
				String port = sshP.getText().toString();
				String uri = "ssh://" + user + "@" + hostName + ":" + port + "/#" + user;
				//Log.i("HostView:onClickListner", "uri is: " + uri);
				//	            	Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("ssh://devendra@komodo.ee.columbia.edu:22/#drl"));
				Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
				//	            	Log.e("sss", "Sending ssh intent");
				try{


					startActivity(i);
				}
				catch(Exception e)
				{
					displayIntentError();

				}
			}


		});
		if(back.requestFocusFromTouch())
		{
			//			Log.i("Hostview", "Got fcus for button");
		}
		//sshP.requestFocus();
		//		sshP.setFocusable(false);
		//		sshU.setFocusable(false);

	}

	private void displayIntentError() {
		Toast.makeText(HostView.this, R.string.view_error_ssh,
				Toast.LENGTH_LONG).show();

		//new AlertDialog.Builder(getBaseContext()).setMessage(R.string.view_error)
		//.setPositiveButton(android.R.string.ok, null).show();
	}

	protected void onStart()
	{
		super.onStart();
		//back.requestFocus();
	}
	protected void onStop()
	{	
		super.onStop();
	}
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);

		MenuItem item;
		item = menu.add(0, DELETE,0, R.string.delete_host);
		item.setIcon(android.R.drawable.ic_menu_delete);
		item = menu.add(0, EDIT,0, R.string.edit_host);
		item.setIcon(android.R.drawable.ic_menu_edit);

		item = menu.add(0, HELP,0, R.string.help);
		item.setIcon(android.R.drawable.ic_menu_help);

		item = menu.add(0, BARCODE,0, R.string.view_barcode);
		item.setIcon(R.drawable.barcode);

		return true;
	}

	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()) {
		case DELETE:

			deleteHost();

			break;
		case EDIT:

			editHost();
			break;

		case HELP:

			displayHelp();
			break;

		case BARCODE:
			addBarcode();
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	private void addBarcode() {
		Intent intent = new Intent("com.google.zxing.client.android.SCAN");
		//intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
		try{
			startActivityForResult(intent, BARCODE);	
		}
		catch(Exception e)
		{
			Toast.makeText(HostView.this, R.string.view_error_barcode,
					Toast.LENGTH_LONG).show();
		}

	}

	private void displayHelp() {

		new AlertDialog.Builder(this).setMessage(R.string.help_view)
		.setPositiveButton(android.R.string.ok, null).show();
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

		super.onActivityResult(requestCode, resultCode, intent);
		if(intent == null)
		{
			return;
		}
		Bundle extras = intent.getExtras();

		switch(requestCode) {
		case BARCODE:
			edited = true;
			backToCalling = true;
			if(extras == null || resultCode != RESULT_OK)
			{
				break;
			}
			gBarcode = intent.getStringExtra("SCAN_RESULT");
			//            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

			barcode.setText("Barcode : " + gBarcode);

			break;
		case EDIT:
			edited = true;
			backToCalling = true;
			if(extras == null)
			{
				break;
			}
			String host = extras.getString(Host.NAME);
			if(host == null)
			{
				break;
			}
			comment.setText(extras.getString(Host.COMMENT));
			gOptPath = extras.getString(Host.OPTPATH);
			
			String sshNew = extras.getString(Host.SSHUSER);
			String sshOld = sshU.getText().toString();


			if(defaultUser.equals(sshOld))
			{	
				// Case 1:- sshOldUser was default, sshNewUser is default
				if(sshNew == null || "".equals(sshNew))
				{
					sshU.setText(defaultUser);
				}
				// Case 2:- sshOldUser was default, sshNewUser is foo
				else
				{
					sshU.setText(sshNew);
				}
			}
			else
			{
				if(sshNew == null || "".equals(sshNew))
					// Case 3:- sshOldUser was foo, sshNewUser is null i.e. default
				{
					sshU.setText(defaultUser);
				}
				// Case 4:- sshOldUser was foo, sshNewUser is foobar
				else
				{
					sshU.setText(sshNew);
				}

				// Similarly for port
				sshNew = extras.getString(Host.SSHPORT);
				sshOld = sshP.getText().toString();

				if(!defPort.equals(sshOld) && (sshNew == null || "".equals(sshNew)))
				{
					sshP.setText(defPort);
				}
				else
				{
					sshP.setText(sshNew);
				}
			}
		}
	}

	/* Capture back button press, and if edited, then send back updated data */
	public boolean onKeyDown(int keyCode, KeyEvent event) 
	{
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) 
		{
			if(edited)
			{
				Intent i = new Intent();
				i.putExtras(createBundle());
				setResult(HOST_EDITED, i);
				edited = false;
			}
			else
			{
				setResult(RESULT_OK);
			}
			finish();
			return true;
		}
		else
			return super.onKeyDown(keyCode, event);
	}


	private void editHost() {
		//TODO
		// Launch the add host activity. Get back edited fields
		// We need to edit only the comments, sshU, sshP
		edited = true;
		Bundle bundle = new Bundle();

		bundle.putString(Host.NAME, name.getText().toString());
		bundle.putString(Host.COMMENT, comment.getText().toString());
		String sU = sshU.getText().toString();
		if(!HostDbAdapter.UNSET_SSHUSER.equals(sU) && !defaultUser.equals(sU))
		{
			bundle.putString(Host.SSHUSER, sU);
		}

		String sP = sshP.getText().toString();

		if(!HostDbAdapter.UNSET_SSHPORT.equals(sP) && !defPort.equals(sP))
		{
			bundle.putString(Host.SSHPORT, sP);
		}
		bundle.putString(Host.OPTPATH, gOptPath);
		
		Intent i = new Intent(this, HostAdd.class);
		i.putExtras(bundle);
		backToCalling = false;
		startActivityForResult(i, EDIT);

	}

	private Bundle createBundle()
	{
		Bundle bundle = new Bundle();

		bundle.putString(Host.NAME, name.getText().toString());
		bundle.putString(Host.COMMENT, comment.getText().toString());
		bundle.putString(Host.SSHUSER, sshU.getText().toString());
		bundle.putString(Host.SSHPORT, sshP.getText().toString());
		bundle.putString(Host.BARCODE, gBarcode);
		bundle.putString(Host.OPTPATH, gOptPath);
		
		return bundle;

	}
	private void deleteHost() {
		Intent i = new Intent();
		i.putExtras(createBundle());

		setResult(HOST_DELETED, i);
		finish();
	}
}